<?php

namespace App\Admin\Controllers\Auth;

use App\Services\JWT\JWTService;
use Encore\Admin\Controllers\AuthController;
use Encore\Admin\Facades\Admin;
use Encore\Admin\Form;
use Illuminate\Http\Request;

class BaseAuthController extends AuthController
{
    protected $role_type = -1;

    public function getLogin()
    {
        $request = request();
        if ($token = $request->get('login_token')) {
            $this->tokenLogin($token);
        } elseif ($request->has('site')) {
            return $this->changeSite($request->get('site') ?: 0);
        }
        return parent::getLogin();
    }

    /**
     * Handle a login request.
     *
     * @param Request $request
     *
     * @return mixed
     */
    public function postLogin(Request $request)
    {
        $this->loginValidator($request->all())->validate();

        $credentials = $request->only([$this->username(), 'password']);
        $remember = $request->get('remember', false);

        $credentials['enabled'] = 1;
        $credentials['role_type'] = $this->role_type;

        if ($this->guard()->attempt($credentials, $remember)) {
            return $this->sendLoginResponse($request);
        }

        return back()->withInput()->withErrors([
            $this->username() => $this->getFailedLoginMessage(),
        ]);
    }

    protected function tokenLogin($token)
    {
        if ($token) {
            $obj = JWTService::decode($token);
            if ($uid = $obj->uid) {
                $role_type = is_array($this->role_type) ? $this->role_type : [$this->role_type];
                if (in_array($obj->type, $role_type)) {
                    Admin::guard()->loginUsingId($uid);
                    admin_toastr('切换成功');
                }
            }
        }
    }

    public function getLogout(Request $request)
    {
        if ($request->has('change')) {
            return $this->changeSite($request->get('change'));
        }
        return parent::getLogout($request);
    }

    protected function changeSite(int $type)
    {
        $uri = data_get(['/user/auth/login', '/admin/auth/login', '/dept/auth/login'], $type);
        $user = Admin::user();
        if (is_null($user) || !$user->role_type || !$uri) {
            return redirect($this->redirectPath());
        }
        //$this->guard()->logout();
        return redirect($uri . '?' . http_build_query([
                'login_token' => JWTService::encode(['uid' => $user['id'], 'type' => $user->role_type], 60)
            ]));
    }

    /**
     * Model-form for user setting.
     *
     * @return Form
     */
    protected function settingForm()
    {
        $class = config('admin.database.users_model');

        $form = new Form(new $class());

        $form->display('username', trans('admin.username'));
        $form->display('name', trans('姓名'));
        $form->password('password', trans('admin.password'))->rules('confirmed|required');
        $form->password('password_confirmation', trans('admin.password_confirmation'))->rules('required')
            ->default(function ($form) {
                return $form->model()->password;
            });
        //$form->image('avatar', trans('admin.avatar'))->uniqueName();
        $form->setAction(admin_url('auth/setting'));

        $form->ignore(['password_confirmation']);

        $form->saving(function (Form $form) {
            if ($form->password && $form->model()->password != $form->password) {
                $form->password = bcrypt($form->password);
            }
        });

        $form->saved(function () {
            admin_toastr(trans('admin.update_succeeded'));

            return redirect(admin_url('auth/setting'));
        });

        return $form;
    }
}
